import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/bad_event/ui/bad_event_list_page.dart';
import 'package:ls_work/doctor_advice/add_doctor_advice_pag.dart';
import 'package:ls_work/util/ext_utils.dart';

import '../net/response/medicine_advice/medicine_advice_list_data.dart';
import '../res/colors.dart';
import '../res/gaps.dart';
import '../viewmodel/medicine_advice/medicine_advice_list_view_model.dart';
import '../viewmodel/new_activity/activity_info_detal_view_model.dart';
import '../widgets/common_widget.dart';
class DoctorAdviceListPage extends BaseStatefulMvvmWidget{
  @override
  State<StatefulWidget> createState() => _MedicineAdviceListState();

}

class _MedicineAdviceListState extends BaseMvvmListState<
    MedicineAdviceListViewModel, DoctorAdviceListPage> {
  GlobalKey<ScaffoldState> key = GlobalKey();

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      key: key,
      appBar: AppBar(
        title: Text('医嘱列表'),
        actions: [IconButton(onPressed: () {
          key.currentState?.openEndDrawer();
        }, icon: Icon(Icons.search))],
      ),
      body: Column(
        children: [
          loadingContentWidget.setWeight(1),
          TextButton(onPressed: () async {
            var data = await Go().push(AddDoctorAdvicePage());
            if(data!=null){
              viewModel.requestRefresh();
            }
          }, child: CommonText('医嘱录入',textColor: Colors.white),style: badEventButtonStyle,).addToContainer(
            margin: EdgeInsets.only(left: 16,right: 16,top: 12,bottom: 20)
          )
        ],
      ),
      endDrawer: endDraw(),
    );
  }

  Widget endDraw() {
    return Column(
      children: [
        AppBar(
          leading: Container(),
          actions: [Container()],
          title: Text('筛选'),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 12,
            ),
            CommonText( '长者姓名 / 房间号'),
            SizedBox(
              height: 8,
            ),
            NoBorderInput(
                hintText: '输入长者姓名 / 房间号',
                text: vm?.customerNameOrBedNoLike ?? "",
                maxLines: 1,
                textInputAction: TextInputAction.search,
                onChanged: (str) {
                  viewModel.customerNameOrBedNoLike = str;
                },
                onSubmitted: (str) {
                  viewModel.requestRefresh();
                })
                .addToContainer(
                decoration: BoxDecoration(
                    color: Colours.bg_color, borderRadius: 6.borderRadius),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5)),
            SizedBox(
              height: 10,
            ),
            CommonText('医嘱类型'),
            SizedBox(
              height: 8,
            ),
            CommonText(vm?.selectedType?.name ?? "", hintText: '请选择')
                .addToContainer(
                width: double.infinity,
                decoration: BoxDecoration(
                    color: Colours.bg_color, borderRadius: 6.borderRadius),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5))
                .onTap(() {
              viewModel.chooseMedicineType();
            }),
            SizedBox(
              height: 10,
            ),
            CommonText('开始日期'),
            SizedBox(
              height: 8,
            ),
            CommonText(vm?.startDateStr, hintText: '请选择')
                .addToContainer(
                width: double.infinity,
                decoration: BoxDecoration(
                    color: Colours.bg_color, borderRadius: 6.borderRadius),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5))
                .onTap(() {
              viewModel.selectStartDate(click: (date){
                viewModel.requestRefresh();
              });
            }),
            SizedBox(
              height: 10,
            ),
            CommonText('结束日期'),
            SizedBox(
              height: 8,
            ),
            CommonText(vm?.endDateStr, hintText: '请选择')
                .addToContainer(
                width: double.infinity,
                decoration: BoxDecoration(
                    color: Colours.bg_color, borderRadius: 6.borderRadius),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5))
                .onTap(() {
              viewModel.selectEndDate(click: (date){
                viewModel.requestRefresh();
              });
            }),
            SizedBox(
              height: 10,
            ),
            CommonText('医嘱确认状态'),
            SizedBox(
              height: 8,
            ),
            CommonText(vm?.selectedConfirm?.pickName, hintText: '请选择')
                .addToContainer(
                width: double.infinity,
                decoration: BoxDecoration(
                    color: Colours.bg_color, borderRadius: 6.borderRadius),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5))
                .onTap(() {
              viewModel.chooseConfirmStatus();
            }),
            SizedBox(
              height: 10,
            ),
            CommonText('医嘱核对状态'),
            SizedBox(
              height: 8,
            ),
            CommonText(vm?.selectedCheck?.pickName, hintText: '请选择')
                .addToContainer(
                width: double.infinity,
                decoration: BoxDecoration(
                    color: Colours.bg_color, borderRadius: 6.borderRadius),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5))
                .onTap(() {
              viewModel.chooseCheckStatus();
            }),
          ],
        ).addToContainer(
          padding: EdgeInsets.symmetric(horizontal: 16),
        ),
        SizedBox().setWeight(1),
        Gaps.dividerLine,
        SizedBox(
          height: 10,
        ),
        Row(
          children: [
            SizedBox(
              width: 16,
            ),
            TextButton(
              onPressed: () {
                key.currentState?.closeEndDrawer();
                viewModel.resetClick();
              },
              child: CommonText('重置', textColor: Colors.blue),
              style: ButtonStyle(
                  shape: MaterialStateProperty.all(RoundedRectangleBorder(
                      borderRadius: BorderRadius.horizontal(left: 20.radius),
                      side: BorderSide(color: Colors.blue)))),
            ).setWeight(1),
            TextButton(
                onPressed: () {
                  key.currentState?.closeEndDrawer();
                  viewModel.requestRefresh();
                },
                child: CommonText('确定', textColor: Colors.white),
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.blue),
                    shape: MaterialStateProperty.all(RoundedRectangleBorder(
                      borderRadius: BorderRadius.horizontal(right: 20.radius),
                      side: BorderSide(color: Colors.blue),
                    )))).setWeight(1),
            SizedBox(
              width: 16,
            ),
          ],
        ),
        SizedBox(
          height: 12,
        )
      ],
    ).addToContainer(
        width: MediaQuery.of(context).size.width * 0.7,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.horizontal(left: 12.radius)));
  }

  @override
  Widget createItemWidget(int index) {
    var item = viewModel.listItems[index];
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 10,),
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            CommonText(item.clientName,
                fontWeight: FontWeight.bold, textSize: 18),
            CommonText(item.bedNo),
            CommonText(item.sexName),
            if (item.age != null) CommonText("${item.age}岁")
          ].insertWidget(SizedBox(
            width: 10,
          )),
        ),
        Row(
          children: [
            CommonText('医嘱类型：'),
            CommonText(item.typeName, textColor: Colors.blue)
          ],
        ),
        CommonText('登记时间：${item.createdDate}'),
        CommonText('医嘱说明：${item.remark ?? ""}'),
        CommonText('医嘱适用时间：${(item.startDate ?? "").changeTime(format: [
          'yyyy',
          '-',
          'mm',
          '-',
          dd
        ])}~${(item.endDate ?? "").changeTime(format: [
          'yyyy',
          '-',
          'mm',
          '-',
          dd
        ])}'),
        CommonText('医嘱登记人：${item.createdByName ?? ""}'),

        Divider(
          height: 1,
          color: Colors.grey,
        ),
        CommonText('详情'),
        ...detailInfoWidget(item),
        SizedBox(height: 8,)

      ].insertWidget(SizedBox(
        height: 8,
      )),
    ).addToContainer(
        decoration:
        BoxDecoration(color: Colors.white, borderRadius: 5.borderRadius),
        padding: EdgeInsets.symmetric(
          horizontal: 10,
        ));
  }

  @override
  MedicineAdviceListViewModel createViewModel() {
    return MedicineAdviceListViewModel(context);
  }

  @override
  bool get canPullUp => true;

  @override
  EdgeInsets get listPadding =>
      EdgeInsets.symmetric(horizontal: 16, vertical: 12);

  @override
  Widget get separatorDivider => SizedBox(
    height: 12,
  );

  List<Widget> detailInfoWidget(MedicineAdviceListData item) {
    var list = <TitleValue>[];

    if (item.typeId == 1) {
      var mpBean = item.mpBean;
      list.addAll([
        TitleValue(title: '药品名称', value: mpBean['medicineInfo']['name']),
        TitleValue(title: '用药类型', value: mpBean['elderMedicineTypeName']),
        TitleValue(title: '给药途径', value: mpBean['useTypeDesc']),
        TitleValue(
            title: '用药频次',
            value:
            "${mpBean['frequencyDesc']}(${mpBean['frequencyRemark'] ?? ""})"),
      ]);

      if (mpBean['useTimeType'] == 0) {
        var infoList = <String>[];
        (mpBean['itemDetail'] as Map<String, dynamic>).forEach((key, value) {
          infoList.add(
              "${key.useTimeName} ${value}${mpBean['takeUnitDesc'] ?? ""}");
        });
        list.add(TitleValue(title: '用药频次', value: infoList.join(" ")));
      } else if (mpBean['useTimeType'] == 1) {
        var infoList = <String>[];
        (mpBean['itemDetail'] as Map<String, dynamic>).forEach((key, value) {
          infoList.add("${key} ${value}${mpBean['takeUnitDesc'] ?? ""}");
        });
        list.add(TitleValue(title: '用药频次', value: infoList.join(" ")));
      }
      list.add(TitleValue(
          title: '用药日期',
          value:
          "${((mpBean['useStartDate'] as String?) ?? "").changeTime(format: [
            'yyyy',
            '-',
            'mm',
            '-',
            'dd'
          ])}~${((mpBean['useEndDate'] as String?) ?? "").changeTime(format: [
            'yyyy',
            '-',
            'mm',
            '-',
            'dd'
          ])}"));
    }

    if (item.typeId == 2) {
      var qcrBean = item.qcrBean;
      var startDate = ((qcrBean['startHappDate'] as String?) ?? "")
          .changeTime(format: ['yyyy', '-', 'mm', '-', 'dd']);
      var endDate = ((qcrBean['endHappDate'] as String?) ?? "")
          .changeTime(format: ['yyyy', '-', 'mm', '-', 'dd']);
      var infoList = (jsonDecode(qcrBean['happTimes']??'[]') as List?) ?? [];
      list.addAll([
        TitleValue(title: '约束类型', value: qcrBean['constraintTypeName']),
        TitleValue(title: '开始日期', value: startDate),
        TitleValue(title: '结束日期', value: endDate),
        TitleValue(title: '辅具', value: qcrBean['equipmentName']),
        TitleValue(title: '约束频次', value: qcrBean['frequencyValue']),
        TitleValue(
            title: '约束时间',
            value: infoList.isEmpty
                ? ""
                : "${infoList.first['startTime'] ?? ""} ~ ${infoList.first['endTime'] ?? ""}"),
        TitleValue(
            title: '是否监测',
            value: qcrBean['monitor'] == 0
                ? '否'
                : qcrBean['monitor'] == 1
                ? '是'
                : ''),
      ]);
      if (qcrBean['monitor'] == 1) {
        list.add(TitleValue(
            title: '监测间隔时间', value: "每隔${qcrBean['monitorTime']}小时"));
      }
    }

    if (item.typeId == 3) {
      var spBean = item.spBean;
      list.addAll([
        TitleValue(title: '服务类型', value: spBean['expenseTypeName']??""),
        TitleValue(title: '服务项目', value: spBean['expenseItemName']??""),
        TitleValue(title: '开始日期', value: spBean['planStartDate']??""),
        TitleValue(title: '结束日期', value: spBean['planEndDate']??""),
        TitleValue(title: '照护频次', value: spBean['frequencyDescr']??""),
        TitleValue(title: '照护时间', value: spBean['frequencyDetail']??""),
        TitleValue(title: '备注', value: spBean['remark']??""),
      ]);
    }

    if (item.typeId == 4) {
      var rrBean = item.rrBean;
      list.addAll([
        TitleValue(title: '辅具', value: rrBean['equipmentName']),
        TitleValue(title: '辅具使用评估', value: item.useEval),
        TitleValue(title: '租聘时间', value: rrBean['time']),
        TitleValue(title: '预计归还时间', value: rrBean['timeBack']),
        TitleValue(title: '是否收费', value: rrBean['status'] == 0 ? '是' : '否'),
        TitleValue(title: '收费模板', value: rrBean['templateName']),
        TitleValue(title: '费用预计', value: (rrBean['price'] as num?).toStringOrNull()??""),
      ]);
    }

    if (item.typeId == 5) {
      var arBean = item.arBean;
      list.addAll([
        TitleValue(title: '食谱', value: arBean['recipesName']),
        TitleValue(title: '补充饮食', value: arBean['replenishName']),
        TitleValue(title: '说明', value: arBean['reamrk']),
        TitleValue(title: '食物性质', value: arBean['shapeName']),
      ]);
    }

    if (item.typeId == 6) {
      var aiBean = item.aiBean;
      list.addAll([
        TitleValue(title: '注射', value: aiBean['drugName']),
        TitleValue(title: '用法', value: aiBean['usageMethodName']),
        TitleValue(
            title: '用量',
            value:
            '每${aiBean['dayNum']}天 早${aiBean['morningNum']}次 中${aiBean['noonNum']}次 晚${aiBean['nightNum']}次'),
      ]);
    }

    if (item.typeId == 7) {
      var asbBean = item.asbBean;
      var spBean = item.spBean;
      list.addAll([
        TitleValue(title: '营养补充剂名称', value: asbBean['name']),
        TitleValue(title: '使用方法', value: asbBean['usageMode']),
        TitleValue(title: '用量', value: asbBean['dosage']),
        TitleValue(title: '照护频次', value: "${spBean['frequencyDescr']}"),
        TitleValue(title: '照护时间', value: "${spBean['frequencyDetail']}"),
      ]);
    }

    if (item.typeId == 8) {
      var aoBean = item.aoBean;
      var infoList = (jsonDecode(aoBean['happTimes']??'[]') as List?) ?? [];
      list.addAll([
        TitleValue(title: '医疗设备', value: aoBean['equipmentName']??""),
        TitleValue(title: '使用频次', value: aoBean['frequencyValue']??""),
        TitleValue(
            title: '使用时间',
            value: infoList.isEmpty
                ? ""
                : "${infoList.first['startTime'] ?? ""} ~ ${infoList.first['endTime'] ?? ""}"),
      ]);
    }

    return list.map((e) {
      return Row(
        children: [CommonText("${e.title}："), CommonText(e.value).setWeight(1)],
      );
    }).toList();
  }
}

extension TypeStringExt on String {
  String get useTimeName {
    switch (this) {
      case "1":
        return "早餐前";
      case "2":
        return "早餐中";
      case "3":
        return "早餐后";
      case "4":
        return "午餐前";
      case "5":
        return "午餐中";
      case "6":
        return "午餐后";
      case "7":
        return "晚餐前";
      case "8":
        return "晚餐中";
      case "9":
        return "晚餐后";
      case "10":
        return "睡前";
      default:
        return "";
    }
  }
}